import React, { PureComponent, Fragment } from 'react';
import { Table, Alert } from 'antd';
import styles from './index.less';
import { autobind } from 'core-decorators';

@autobind
class StandardTable extends PureComponent {

  static defaultProps = {
    selectedRows: [],
    childColumns: [],
    childData: null,
    rowShow: true,
  };

  constructor(props) {
    super(props);

    this.state = {
      selectedRowKeys: [],
    };
  }

  componentWillReceiveProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      this.setState({
        selectedRowKeys: [],
      });
    }
  }

  handleRowSelectChange(selectedRowKeys, selectedRows) {
    const { onSelectRow } = this.props;

    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys });
  }

  handleTableChange(pagination, filters, sorter) {
    const { onChange } = this.props;
    onChange(pagination, filters, sorter);
  }

  cleanSelectedKeys() {
    this.handleRowSelectChange([], []);
  }

  render() {
    const { selectedRowKeys } = this.state;
    const { data, paging, loading, columns, rowKey, selectedRows, childColumns, rowShow } = this.props;

    if (paging) {
      paging.total = Number.parseInt(paging.total);
    }

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      hideOnSinglePage: true,
      showTotal: (total, range) => `当前${range[1]}项,总共${total}项`,
      ...paging,
    };

    const rowSelection = rowShow ? {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      // getCheckboxProps: record => ({
      //   disabled: record.disabled,
      // }),
    } : null;

    const expandedRowRender = childColumns.length > 0 ? this.renderExpandedRow : null;

    return (
      <div className={styles.standardTable}>
        <div className={styles.tableAlert}>
          {rowShow && <Alert
            message={
              <Fragment>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
                <a onClick={this.cleanSelectedKeys} style={{ marginLeft: 24 }}>
                  清空
                </a>
              </Fragment>
            }
            type="info"
            showIcon
          />}
        </div>
        <Table
          loading={loading}
          rowKey={rowKey || 'key'}
          rowSelection={rowSelection}
          dataSource={data}
          columns={columns}
          expandedRowRender={expandedRowRender}
          pagination={paginationProps}
          onChange={this.handleTableChange}
        />
      </div>
    );
  }

  renderExpandedRow(record) {
    const { loading, rowKey, childColumns, childData } = this.props;
    return (
      <Table
        rowKey={rowKey || 'key'}
        loading={loading}
        dataSource={record[childData]}
        columns={childColumns}
        pagination={false}
      />
    );
  };
}

export default StandardTable;
